package com.qf.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

// 路径收参，参数用来标识发送请求的浏览器
@ServerEndpoint("/websocket/{userid}")
@Component
public class WebSocketController {

    public static final HashMap<String,Session> sessionMap
            = new HashMap<>();

    /**
     * 当浏览器跟服务器建立websocket连接时，要处理的逻辑写在这个方法里
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userid") String userid) throws IOException {

        System.out.println("有连接建立了：userid="+userid);
        sessionMap.put(userid,session);

        session.getBasicRemote().sendText("hello "+userid+" from server");

    }

    /**
     *
     * @param session 连接对象
     * @param userid  连接对象的唯一标识
     * @param msg     发送过来的消息
     */
    @OnMessage
    public void onMsg(Session session,@PathParam("userid") String userid,String msg) throws IOException {

        System.out.println("接收到了消息:userid="+userid+",msg="+msg);
        // 服务器回复消息
//        session.getBasicRemote().sendText("server echo:"+msg);

        // 广播
//        Collection<Session> sessions = sessionMap.values();
//        for (Session s : sessions) {
//            s.getBasicRemote().sendText(" from server:"+msg);
//

        // 给指定的用户发送消息
        String[] split = msg.split(",");
        String uid = split[0];
        String content = split[1];

        Session s = sessionMap.get(uid);
        s.getBasicRemote().sendText(content);

    }


    /**
     * 断开连接的处理逻辑
     * @param session
     * @param userid
     */
    @OnClose
    public void onClose(Session session,@PathParam("userid") String userid){
        System.out.println("断开连接了，userid="+userid);
        sessionMap.remove(userid);// 删除map中的session对象
    }

}
